package cn.dong.order.service.impl;

import cn.dong.api.domain.ResultCodeEnum;
import cn.dong.api.utils.ExceptionUtils;
import cn.dong.api.utils.HttpClientUtils;
import cn.dong.base.handler.CustomException;
import cn.dong.order.domain.TradeOrder;
import cn.dong.order.service.TradeOrderService;
import cn.dong.order.service.WxPayService;
import cn.dong.order.utils.WxPayProperties;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private TradeOrderService tradeOrderService;
    @Autowired
    private WxPayProperties wxPayProperties;

    /**
     * 获取二维码
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map getQrcodeUrl(String orderNo, String ip) {

        try {
            // 根据订单号，获取订单信息
            QueryWrapper<TradeOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            TradeOrder order = tradeOrderService.getOne(queryWrapper);
            // 设置参数
            Map<String, String> m = new HashMap<>(7);
            m.put("out_trade_no", orderNo);
            m.put("body", order.getCourseTitle());
            m.put("notify_url", wxPayProperties.getNotifyUrl());
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("total_fee", (order.getTotalFee().multiply(new BigDecimal(100)).longValue()) + "");
            m.put("appid", wxPayProperties.getAppId());
            m.put("mch_id", wxPayProperties.getPartner());
            m.put("trade_type", "NATIVE");
            m.put("spbill_create_ip", ip);

            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, wxPayProperties.getPartnerKey()));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            // 判断错误异常
            if (!"SUCCESS".equals(resultMap.get("result_code"))
                    || !"SUCCESS".equals(resultMap.get("return_code"))) {
            }

            // 补充流水号等信息
            resultMap.put("orderNo", orderNo);
            resultMap.put("totalFee", order.getTotalFee() + "");
            resultMap.put("courseId", order.getCourseId() + "");

            return resultMap;
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new CustomException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
    }
}
